package com.simple.dsrouter.proxy;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import com.simple.dsrouter.exception.DataSourceRouteException;
import com.simple.dsrouter.holder.DataSourceContextHolder;
import com.simple.dsrouter.strategy.RouteStrategy;

/**
 * 数据源切面
 */
public class DataSourceAspect {
	/**
	 * 路由策略
	 */
	private RouteStrategy routeStrategy;

	private String lastDataSourceKey;

	public void before(JoinPoint point) {
		lastDataSourceKey = DataSourceContextHolder.getCurrentDataSourceKey();
		if (routeStrategy == null) {
			throw new DataSourceRouteException("routeStrategy must not be null");
		}
		Object target = point.getTarget();
		Object[] args = point.getArgs();
		Method method = null;
		try {
			MethodSignature signature = (MethodSignature) point.getSignature();
			if (signature != null) {
				method = signature.getMethod();
			}
		} catch (ClassCastException e) {
			throw new DataSourceRouteException(e);
		}
		if (target != null && method != null && args != null) {
			try {
				routeStrategy.route(target, method, args);
			} catch (Exception e) {
				throw new DataSourceRouteException(target + " method:" + method.getName() + " routing occur error", e);
			}
		}
	}

	public void after(JoinPoint point) {
		DataSourceContextHolder.setCurrentDataSourceKey(lastDataSourceKey);
	}

	public void setRouteStrategy(RouteStrategy routeStrategy) {
		this.routeStrategy = routeStrategy;
	}

}
